package com.middlegroup.payadmin.controller.sys;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.middlegroup.common.annotation.AllLog;
import com.middlegroup.common.exception.BusinessException;
import com.middlegroup.payadmin.controller.BaseController;
import com.middlegroup.payadmin.pojo.dto.DataGrid;
import com.middlegroup.payadmin.pojo.dto.SubjectDto;
import com.middlegroup.payadmin.pojo.message.ApiResult;
import com.middlegroup.payadmin.pojo.po.*;
import com.middlegroup.payadmin.service.ChannelsService;
import com.middlegroup.payadmin.service.MerchantSubjectChannelRouterService;
import com.middlegroup.payadmin.service.SubjectChannelsService;
import com.middlegroup.payadmin.service.SubjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * Created by pc on 2019/1/9.
 */
@Controller
@RequestMapping("/sys/subject")
@Api(value = "主体管理", description = "主体管理", tags = "1.2")
@Valid
public class SubjectController extends BaseController {

    @Resource
    private SubjectService subjectService;

    @Resource
    private ChannelsService channelsService;

    @Resource
    private SubjectChannelsService subjectChannelsService;




    @ApiIgnore
    @GetMapping("/list")
    public String list() {
        return "sys/subject/list";
    }

    @ApiIgnore
    @GetMapping(value = "/edit")
    public String edit(Long id) {
        if (id != null) {
            Subject subject = this.subjectService.selectById(id);
            if (null == subject){
                throw BusinessException.notFound("该数据已失效");
            }else {
                request.setAttribute("dto",subject);
            }
        }
        return "sys/subject/edit";
    }

    @ApiIgnore
    @GetMapping(value = "/config")
    public String config(Long id) {
        if (id != null) {
            Subject subject = this.subjectService.selectById(id);
            if (null == subject){
                throw BusinessException.notFound("该数据已失效");
            }else {
                request.setAttribute("dto",subject);
            }
        }
        return "sys/subject/config";
    }

    @ApiOperation(value = "带条件分页查询")
    @GetMapping(value = "/getConfigs")
    @ResponseBody
    public PageInfo<SystemCfg> getConfigs(String code) {
        if (StringUtils.isNotBlank(code) && code.endsWith(",")){
            code = code.replace(",","");
        }
        return subjectService.getConfigs(code);
    }

    @ApiOperation(value = "带条件分页查询")
    @GetMapping(value = "/query")
    @ResponseBody
    public PageInfo<SubjectDto> query(DataGrid grid, String name,String code) {
        return this.subjectService.listSubjectByName(grid, name,code);
    }

    @ApiOperation(value = "根据主体id获取该主题目前的渠道绑定信息")
    @GetMapping(value = "/getSubjectChannels")
    @ResponseBody
    public List<Channels> getSubjectChannels(String serviceType,@NotNull(message = "主体编码不能为空!")  String subjectCode) {
        return this.subjectChannelsService.waitChannelsList(serviceType,subjectCode);
    }

    @ApiOperation(value = "添加/修改主体信息")
    @AllLog(module = "主体管理", methods = "保存主体", description = "添加/修改主体信息")
    @PostMapping(value = "/save")
    @ResponseBody
    @Transactional(readOnly = false)
    public ApiResult<Subject> save(Subject dto) {

        if (dto.getId() == null) {
            //生成code
            String code = RandomStringUtils.randomAlphanumeric(6);
            dto.setCode(code);
        }
        if (StringUtils.isNotBlank(dto.getSelectCodes())){
            if (dto.getSelectCodes().endsWith(",")){
                //去掉最后一个逗号
                dto.setSelectCodes(dto.getSelectCodes().substring(0,dto.getSelectCodes().length()-1));
            }
            String selects = dto.getSelectCodes();
            String[] selectArr = selects.split(",");
            for (String selectCode : selectArr){
                //插入或者更新
                SubjectChannels subjectChannels = new SubjectChannels();
                subjectChannels.setChannelCode(selectCode);
                subjectChannels.setSubjectCode(dto.getCode());
                subjectChannelsService.saveOrUpdate(subjectChannels);
            }
        }
        if (StringUtils.isNotBlank(dto.getUnselectCodes())){
            if (dto.getUnselectCodes().endsWith(",")){
                //去掉最后一个逗号
                dto.setUnselectCodes(dto.getUnselectCodes().substring(0,dto.getUnselectCodes().length()-1));
            }
            String unselects = dto.getUnselectCodes();
            String[] selectArr = unselects.split(",");
            for (String selectCode : selectArr){
                //插入或者更新
                EntityWrapper<SubjectChannels> entityWrapper = new EntityWrapper<>();
                entityWrapper.where("subject_code={0} and channel_code={1}",dto.getCode(),selectCode);
                subjectChannelsService.delete(entityWrapper);
            }
        }
        if (dto.getId() != null){
            return ApiResult.getResponse(this.subjectService.updateById(dto));
        }else {
            return ApiResult.getResponse(this.subjectService.insert(dto));
        }
    }

    @ApiOperation(value = "删除主体信息")
    @AllLog(module = "主体管理", methods = "移除主体", description = "删除公司主体信息")
    @PostMapping(value = "/remove")
    @ResponseBody
    public ApiResult<String> del(Integer[] ids) {
        Lists.newArrayList(ids).forEach(this.subjectService::deleteById);
        return ApiResult.SUCCESS;
    }

    @ApiOperation(value = "删除主体配置信息")
    @AllLog(module = "主体管理", methods = "移除主体配置", description = "删除公司主体配置信息")
    @PostMapping(value = "/removeSubjectConfig")
    @ResponseBody
    public ApiResult<String> removeSubjectConfig(@NotNull(message = "主体编码不能为空!") String subjectCode,@NotNull(message = "目录不可为空!") String category,@NotNull(message = "配置名不能为空!") String name) {
        return ApiResult.getResponse(subjectService.removeSubjectConfig(subjectCode,category,name));
    }

    @ApiOperation(value = "添加或者编辑主体配置信息")
    @AllLog(module = "主体管理", methods = "添加或者编辑主体配置", description = "添加或者编辑公司主体配置信息")
    @PostMapping(value = "/saveSubjectConfig")
    @ResponseBody
    public ApiResult<String> saveSubjectConfig(@NotNull(message = "主体编码不能为空!") String subjectCode,@NotNull(message = "目录不能为空!") String category,@NotNull(message = "配置名不能为空!") String name,String content,String remark) {
        return ApiResult.getResponse(subjectService.saveSubjectConfig(subjectCode,category,name,content,remark));
    }
}
